package com.abu.authms.controller;

import com.abu.authms.client.UcenterClient;
import com.abu.authms.utils.JwtUtils;
import com.abu.ucenter.pojo.Member;
import com.abu.ucenter.pojo.UserInfo;
import com.abu.utils.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("auth/member")
@RestController
public class AuthController {

    @Autowired
    private UcenterClient ucenterClient;

    @PostMapping("login")
    public Resp login(@RequestBody UserInfo userInfo, HttpServletRequest request, HttpServletResponse response) {
//        远程调用获取用户信息
        Member member = this.ucenterClient.queryMemberByPhoneAndPassword(userInfo);
        if (member == null) {
            return Resp.error();
        }
//        获取用户id和用户名
        String memberId = member.getId();
        String nickname = member.getNickname();
//        生成token
        String token = null;
        try {
            token = JwtUtils.getJwtToken(memberId, nickname);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Resp.ok().data("token", token);
    }


    @GetMapping("getMemberInfo")
    public Resp getLoginUserInfo(HttpServletRequest request) {
//        1.根据request获取memberId
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
//        2.根据memberId获取用户信息
        Member member = this.ucenterClient.queryMemberById(memberId);
//        3.返回用户信息
        if (member == null) {
            return Resp.error().message("用户名或密码有误");
        }
        return Resp.ok().data("userInfo", member);
    }

}
